package com.wtwd.device.aspect;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.device.constant.Constant;
import com.wtwd.device.service.AppUserService;
import com.wtwd.device.util.JWTUtil;
import com.wtwd.device.util.StringUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author zdl
 * @date 2023/10/24 14:28
 */

@Component
@Aspect
public class AppUserServiceAspect {

    @Resource
    private AppUserService appUserService;


    @Before("execution(* com.wtwd.device.controller.AppUserController.*(..))")
    public void notLogin(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object o : args) {
            if (o instanceof JSONObject) {
                JSONObject json = (JSONObject) o;
                Long appId = json.getLong("appId");
                appUserService.setLocalApp(appId);
                return;
            } else {
                Long appId = (Long) o;
                appUserService.setLocalApp(appId);
                return;
            }

        }

    }

    @Before("execution(* com.wtwd.device.service.AppUserService.getCurrentUserId(..))")
    public void Login(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        if (StringUtil.isNotEmpty(token)) {
            String appId = JWTUtil.getClaim(token, "appId", String.class);
            if (StringUtil.isEmpty(appId)) {
                appId = "1";
            }
            appUserService.setLocalApp(Long.valueOf(appId));
        }
    }
}
